package com.mti.ftp.controller;

import com.mti.ftp.service.FtpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/ftp")
@Api(tags = "FTP传输接口")
public class FtpController {

    private final FtpService ftpService;

    public FtpController(FtpService ftpService) {
        this.ftpService = ftpService;
    }

    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");

    @PostMapping("/upload")
    @ApiOperation("FTP-文件上传")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 将上传的文件保存到临时目录
            Path tempFilePath = Paths.get(TEMP_DIR, file.getOriginalFilename());
            // 将MultipartFile内容复制到临时文件
            Files.copy(file.getInputStream(), tempFilePath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            ftpService.uploadFile(tempFilePath.toFile());
            return ResponseEntity.ok("File uploaded successfully.");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to upload file: " + e.getMessage());
        }
    }

    @GetMapping("/download")
    @ApiOperation("FTP-文件下载")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam(value = "remotePath") @ApiParam("服务器文件地址") String remotePath) {
        try {
            // 获取文件输入流
            InputStream inputStream = ftpService.downloadFile(remotePath);
            // 获取文件名
            String fileName = getFileNameFromPath(remotePath);
            // 构建响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 使用 RFC 5987 标准编码文件名
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                    .replaceAll("\\+", "%20"); // 将空格替换为 %20

            // 设置 Content-Disposition 头
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 返回文件流作为响应
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(getFileSize(remotePath)) // 可选：如果需要设置文件大小
                    .body(new InputStreamResource(inputStream));
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    private String getFileNameFromPath(String remotePath) {
        return remotePath.substring(remotePath.lastIndexOf('/') + 1);
    }

    private long getFileSize(String remotePath) throws IOException {
        // 实现获取文件大小的逻辑，可以根据 FTPClient 的方法实现
        // 例如：ftpClient.getSize(remotePath)
        // 这里假设我们不实现此功能，返回 -1 表示未知大小
        return -1;
    }


}